/**
 * Copyright (c) 2006-2007 Jinyi.lu
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of GNU LGPL license by gun.org
 * which accompanies this distribution, and is available at
 * http://gnu.feld-it.at/copyleft/lesser.html
 * 
 * Project Homepage : http://code.google.com/p/demou
 * Source Code: svn checkout http://demou.googlecode.com/svn/trunk/ demou
 * Mailing list : jinyi.lu@gmail.com
 *                stonelu@126.com
 *
 *  
 * Contributors:
 *     JinYi.Lu - initial API and implementation
 */
package cn.tworen.demou.remoting;

import java.util.regex.Pattern;

import net.sf.cindy.Buffer;
import net.sf.cindy.Packet;
import net.sf.cindy.PacketDecoder;
import net.sf.cindy.Session;
import net.sf.cindy.util.Charset;

import org.apache.log4j.Logger;

/**
 * <code>HttpRequest</code> Decoder.
 * 
 * @author <a href="chenrui@gmail.com">Roger Chen</a>
 * @version $id$
 */
public class HttpRequestDecoder implements PacketDecoder {

    private static final byte[] TOKEN = "\r\n\r\n".getBytes();
    private static final Pattern PATTERN = Pattern.compile(" ");
    private static final Logger logger = Logger.getLogger(HttpRequestDecoder.class);
    public Object decode(Session session, Packet packet) throws Exception {
        Buffer buffer = packet.getContent();
//        logger.debug(buffer.dump());
        int index = buffer.indexOf(TOKEN);
        if (index >= 0) {
            String[] headers = buffer.getString(Charset.UTF8,
                    index + TOKEN.length).split("\r\n");

            HttpRequest request = new HttpRequest();
            parse(request, headers);

            String contentLen = request.getParam("Content-Length");
            if (contentLen != null) {
                int len = Integer.parseInt(contentLen);
                if (buffer.remaining() >= len) {
                    byte[] content = new byte[len];
                    buffer.get(content);
                    request.setContent(content);
                } else {
                    return null;
                }
            } else if (buffer.hasRemaining()) {
            	byte[] content = new byte[buffer.remaining()];
            	buffer.get(content);
            	request.setContent(content);
            }
            return request;
        }
        return null;
    }

    private void parse(HttpRequest request, String[] headers) {
        // every time use String.split will construct a new Pattern object
        String[] s = PATTERN.split(headers[0]);
        request.setRequestMethod(s[0]);
        request.setRequestURI(s[1]);
        request.setVersion(s[2]);

        for (int i = 1; i < headers.length; i++) {
            int index = headers[i].indexOf(":");
            request.setParam(headers[i].substring(0, index).trim(), headers[i]
                    .substring(index + 1).trim());
        }
    }
}
